#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import os
import web
import json
from Umpweb.common import log
from Umpweb.db import api as db_api
from Umpweb.common import utils, config
from Umpweb.base import session, _, render_jinja
from Umpweb.common.utils import login_required, grid_json


LOG = log.get_log('Umpweb.webapps.schedule')


urls = ( 
        '/create',          'SchduleCreate',
        '/update',          'SchduleUpdate',
        '/delete',          'SchduleDelete',
        '/job/create',      'ScheduleJobCreate',
        '/job/delete',      'ScheduleJobDelete',
        '/job/list',        'ScheduleJobList',
        '/job/grid',        'GridScheduleJob',
        '/report/list',     'ScheduleReportList',
        '/report/grid',     'GridScheduleReport',
        '/report/download', 'ScheduleReportDownload',
        '/report/delete',   'ScheduleReportDelete',
        '/result',          'TaskResult',
)

app = web.application(urls, locals())
render = render_jinja('static/templates/schedule', encoding='utf-8',)


class SchduleCreate:

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = dict(**x)
        body = {"ScheduleCreate":{'params':values}}
        return utils.web_return(body)

class SchduleUpdate:

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = dict(**x)
        body = {"ScheduleUpdate":{'params':values}}
        return utils.web_return(body)


class ScheduleJobList():
    @login_required
    def GET(self):
        web.header("Content-Type", "text/plain")
        return render.job_list()


class GridScheduleJob():
    def GET(self):
        web_input = web.input()
        filters = {'class_name': 'ReportIopsJob', 'deleted': False}
        page, total, records, rows = utils.grid_rows_query(db_api.schedule_job_table, web_input, filters=filters)

        for row in rows:
            if row.context:
                row.report_name = row.context.get('report_name')
                row.report_type = row.context.get('report_type')
                row.type_name = row.context.get('type_name')
                row.start_time = row.context.get('start_time')
                row.end_time = row.context.get('end_time')
                row.interval_time = row.context.get('interval_time')

        cells = ['id', 'report_name', 'report_type', 'type_name',
                 'start_time', 'end_time', 'interval_time', 'owner', 'created_at', 'status']
        rows_json = grid_json(page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json


class ScheduleJobCreate():
    @login_required
    def GET(self):
        clusters = db_api.cluster_get_all()
        hosts = []
        pools = db_api.pool_get_with_user(web.config._session.user.id)
        volumes = db_api.volume_get_with_user(web.config._session.user.id)
        if db_api.check_is_adminstrator(web.config._session.user.name):
            hosts = db_api.host_get_all()
            pools = db_api.pool_get_all()
            volumes = db_api.volume_get_all()
        username  = web.config._session.user.name
        if not db_api.check_is_adminstrator(username):
            return render.job_create(super={'p':''}, pools=pools, volumes=volumes,)
        else:
            return render.job_create( clusters=clusters, hosts=hosts, pools=pools, volumes=volumes, super={'p':'y'})

    @login_required
    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        values = dict(**x)

        if values['report_type'] == 'cluster':
            cluster_id = values['type_id']
            cluster = db_api.cluster_get(cluster_id)
            values['type_name'] = json.loads(cluster.config_str)['globals.clustername']

        elif values['report_type'] == 'host':
            host_id = values['type_id']
            host = db_api.host_get(host_id)
            values['type_name'] = host.ip

        elif values['report_type'] == 'pool':
            pool_id = values['type_id']
            pool = db_api.pool_get(pool_id)
            values['type_name'] = pool.path

        else:
            volume_id = values['type_id']
            volume = db_api.volume_get(volume_id)
            values['type_name'] = volume.path

        body = {"ScheduleJobCreate": {'params': values}}
        return utils.web_return(body)


class ScheduleJobDelete():
    @login_required
    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        body = {"ScheduleJobDelete": {'params': {'id': x.get('id').strip()}}}
        return utils.web_return(body)


class ScheduleReportList():
    @login_required
    def GET(self):
        web.header("Content-Type", "text/plain")
        return render.job_list()


class GridScheduleReport():
    def GET(self):
        web_input = web.input()
        filters = {'type': 'iops'}
        page, total, records, rows = utils.grid_rows_query(db_api.schedule_job_report_table, web_input, filters=filters)
        cells = ['id', 'name', 'owner', 'created_at']
        rows_json = grid_json(page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json


class ScheduleReportDownload():
    @login_required
    def GET(self):
        install_dir = os.path.abspath(os.path.split(os.path.realpath(__file__))[0] + "/../../../..")
        report_path = '%s/tmp/ump/report/' % install_dir
        x = web.input()
        report = db_api.schedule_job_report_get(x.get('id'))

        report_name = report.name + '.csv'
        report_path_name = os.path.join(report_path, report_name)
        try:
            f = open(report_path_name, "rb")
            web.header('Content-Type', 'application/octet-stream')
            web.header('Content-disposition', 'attachment; filename=%s' % report_name)
            while True:
                c = f.read()
                if c:
                    yield c
                else:
                    break
        except Exception, e:
            LOG.info('%s' % (e))
            yield 'Error'
        finally:
            if f:
                f.close()


class ScheduleReportDelete():
    @login_required
    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()
        body = {"ScheduleReportDelete": {'params': {'id': x.get('id').strip()}}}
        return utils.web_return(body)


class TaskResult:

    def GET(self):

        return render.task_result()